package org.alino.core.freemarker.base;


import org.alino.core.filter.data.Page;
import org.alino.core.utils.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Desc TODO
 * @Author by Brant
 * @Date 2016/12/26
 */
public abstract class BasePaginateTag extends BaseTag {
    public static final String PAGER_LOAD_TYPE_AJAX = "ajax";
    public static final String PAGER_LOAD_TYPE_DEFAULT = "default";
    private String previousClass;
    private String nextClass;
    private String activeClass;
    private String disabledClass;
    private String anchor;
    private boolean onlyShowPreviousAndNext = false;
    private String loadType;
    private String pageContainer;
    private Integer showNum;

    final Page<?> page;

    public BasePaginateTag(Page<?> page){
        this.page = page;
    }

    @Override
    public void onRender() {
        loadType = getParam("loadType", PAGER_LOAD_TYPE_AJAX);   //ajax无刷新 default常规
        pageContainer = getParam("container", ".alino-container");   //ajax无刷新 default常规
        previousClass = getParam("previousClass", "previous");
        nextClass = getParam("nextClass", "next");
        activeClass = getParam("activeClass", "active");
        disabledClass = getParam("disabledClass", "disabled");
        showNum = getParamToInt("showNum",10);
        anchor = getParam("anchor");
        onlyShowPreviousAndNext = getParamToBool("onlyShowPreviousAndNext", false);

        String previousText = getParam("previousText", "上一页");
        String nextText = getParam("nextText", "下一页");

        int currentPage = page.getPageNumber();
        int totalPage = page.getToltalPage();

        List<PaginateItem> pages = new ArrayList<PaginateItem>();
        //---------------------------------
        // 当前页不是第一页，
        // 还要加入第一页和上一页标签
        //---------------------------------
        if (currentPage == 1) {
            pages.add(new PaginateItem(previousClass + " " + disabledClass, "javascript:;", previousText));
        } else {
            pages.add(new PaginateItem(previousClass, getUrl(currentPage - 1), previousText));
        }
        if(!onlyShowPreviousAndNext) {
            //---------------------------------
            // 如果当前页大于每页显示页码数。
            // 则要显示快速向上翻的标签(标签是：...)
            //---------------------------------
            int currentNum = (page.getPageNumber() % showNum == 0 ? (page.getPageNumber() / showNum) - 1 : page.getPageNumber() / showNum) * showNum;
            if (currentNum < 0) currentNum = 0;
            if (currentPage > showNum) {
                pages.add(new PaginateItem("", getUrl(currentNum - showNum + 1), "..."));
            }
            if (page.getToltalPage() == 1) {
                pages.add(new PaginateItem(disabledClass, "javascript:;", "1"));
            }
            //---------------------------------
            // 显示中间可用的翻页码
            //---------------------------------
            for (int i = 0; i < showNum; i++) {
                if ((currentNum + i + 1) > page.getToltalPage() || page.getToltalPage() < 2) break;
                if (currentNum + i + 1 == page.getPageNumber()) {
                    pages.add(new PaginateItem(activeClass, "javascript:;", currentNum + i + 1));
                } else {
                    pages.add(new PaginateItem("", getUrl(currentNum + i + 1), currentNum + i + 1));
                }
            }
            //---------------------------------
            // 如果还未到达最后一版，
            // 则还要加入快速向下翻的标签(标签是：...)
            //---------------------------------
            if (page.getToltalPage() > (currentNum + showNum)) {
                pages.add(new PaginateItem("", getUrl(currentNum + 1 + showNum), "..."));
            }
        }
        //---------------------------------
        // 如果当前页不是最后一页，
        // 则要加入下一页和最后一页标筌
        //---------------------------------
        if(totalPage==0){
            pages.add(new PaginateItem(nextClass + " " + disabledClass, "javascript:;", nextText));
        }else{
            if (currentPage == totalPage) {
                pages.add(new PaginateItem(nextClass + " " + disabledClass, "javascript:;", nextText));
            } else {
                pages.add(new PaginateItem(nextClass, getUrl(currentPage + 1), nextText));
            }
        }

        setVariable("pages", pages);
        renderBody();
    }

    protected abstract String getUrl(int pageNumber);

    public String getPreviousClass() {
        return previousClass;
    }

    public String getNextClass() {
        return nextClass;
    }

    public String getActiveClass() {
        return activeClass;
    }

    public String getDisabledClass() {
        return disabledClass;
    }

    public String getAnchor() {
        return anchor;
    }

    public boolean isOnlyShowPreviousAndNext() {
        return onlyShowPreviousAndNext;
    }

    public String getLoadType() {
        return loadType;
    }

    public String getPageContainer() {
        return pageContainer;
    }

    public Map<String, String> getAllRequestParam(HttpServletRequest request) {
        Map<String, String> res = new HashMap<String, String>();
        Enumeration<?> temp = request.getParameterNames();
        if (null != temp) {
            while (temp.hasMoreElements()) {
                String en = (String) temp.nextElement();
                String value = request.getParameter(en);
                res.put(en, StringUtils.unEscapeString(value));
                if (null == res.get(en) || "".equals(res.get(en))) {
                    res.remove(en);
                }
            }
        }
        return res;
    }

    public String getQueryStringByV1(HttpServletRequest request){
        return getQueryStringByV1(getAllRequestParam(request));
    }

    public static String getQueryStringByV1(Map<String, String> params) {
        if(params == null) {
            return "";
        } else {
            if(params.keySet().contains("p"))
                params.remove("p");
            StringBuffer content = new StringBuffer();
            ArrayList keys = new ArrayList(params.keySet());
            for(int i = 0; i < keys.size(); ++i) {
                String key = (String)keys.get(i);
                String value = (String)params.get(key);
                content.append((i == 0?"":"&") + key + "=" + value);
            }
            return content.toString();
        }
    }

    public static class PaginateItem {
        private String style;
        private String url;
        private String text;

        public PaginateItem(String style, String url, String text) {
            this.style = style;
            this.url = url;
            this.text = text;
        }

        public PaginateItem(String style, String url, int text) {
            this.style = style;
            this.url = url;
            this.text = text + "";
        }

        public String getStyle() {
            return style;
        }

        public void setStyle(String style) {
            this.style = style;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }
    }
}
